package org.grow.safety.controller;

import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.authfilter.entity.RoleInfo;
import org.grow.safety.dao.RouteConfigDao;
import org.grow.safety.entity.QRoleInfo;
import org.grow.safety.entity.QRoleRoute;
import org.grow.safety.entity.RouteConfig;
import org.grow.safety.entity.QRouteConfig;
import org.grow.safety.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: xwg
 * @CreateDate: 21-8-2
 */

@RestController
@RequestMapping("/safety/secure")
public class SecureController {
    @GetMapping("/testMvc")
    public String testMvc(){
        return LocalDateTime.now().toString();
    }


    @Autowired
    private RouteConfigDao routeConfigDao;
    @GetMapping("/allRoutes")
    public List<RouteConfig> allRoutes(){
        return routeConfigDao.findAll();
    }
    /**
    * select distinct rc.* from RoleInfo r
     * inner join RoleRoute rr on r.roleId = rr.roleFk
     * inner join RouteConfig rc on rr.routeFk = rc.routeId
     * # where r.roleId =1;
     * where r.roleId in (1,2);
    *
    * */

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    QRoleInfo r = QRoleInfo.roleInfo;
    QRoleRoute rr = QRoleRoute.roleRoute;
    QRouteConfig rc = QRouteConfig.routeConfig;
    @GetMapping("/roleRoutes")
    public List<RouteConfig> roleRoutes(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        List<RoleInfo> authorities = (List<RoleInfo>) authentication.getAuthorities();
        List<Integer> roleIds = authorities.stream().map(x -> x.getRoleId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(roleIds)) return Collections.emptyList();
        List<RouteConfig> fetch = jpaQueryFactory.selectDistinct(rc)
                .from(r).innerJoin(rr).on(r.roleId.eq(rr.roleFk))
                .innerJoin(rc).on(rr.routeFk.eq(rc.routeId))
                .where(r.roleId.in(roleIds))
                .orderBy(rc.routeId.asc())
                .fetch();
        return fetch;
    }
 }
